package com.ctyun.xstore.s3.client;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;

/**
 * S3客户端类
 * 参考文档:
 * https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html
 * https://docs.aws.amazon.com/AmazonS3/latest/API/archive.html
 * 参考代码：https://github.com/awsdocs/aws-doc-sdk-examples
 */
public class AmazonS3ClientBuilder {
    //设置endPoint(不含bucketName前缀)、accessKey、secretKey
    private static String endPoint = "";
    private static String accessKey = "";
    private static String secretKey = "";

    public static AmazonS3 buildAmazonS3Client() {
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(endPoint, Regions.CN_NORTH_1.getName());
        AmazonS3 s3Client = com.amazonaws.services.s3.AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withEndpointConfiguration(endpointConfiguration)
                .build();
        return s3Client;
    }

    /**
     * 根据临时ak、sk、token生成s3客户端
     * @param accessKey
     * @param secretKey
     * @param sessionToken
     * @param endPoint
     * @return
     */
    public static AmazonS3 buildSessionCredentialsAmazonS3Client(String accessKey, String secretKey, String sessionToken,String endPoint) {
        BasicSessionCredentials credentials = new BasicSessionCredentials(accessKey,secretKey,sessionToken);
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(endPoint, Regions.CN_NORTH_1.getName());
        AmazonS3 s3Client = com.amazonaws.services.s3.AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withEndpointConfiguration(endpointConfiguration)
                .build();
        return s3Client;
    }

}
